In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be Immutable object and the length changed, or it may be fixed (after creation). A string is often implemented as an array data structure of (or words) that stores a sequence of elements, typically characters, using some character encoding. More general, string may also denote a sequence (or list) of data other than just characters.
Depending on the programming language and precise data type used, a variable declared to be a string may either cause storage in memory to be statically allocated for a predetermined maximum length or employ dynamic allocation to allow it to hold a variable number of elements.
When a string appears literally in source code, it is known as a string literal or an anonymous string.
In , which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set called an alphabet.
Example strings and their purposes:
The term string may also designate a sequence of data or computer records other than characters, like a "string of ", but when used without qualification it refers to strings of characters.
Use of the word "string" to mean "a sequence of symbols or linguistic elements in a definite order" emerged from mathematics, symbolic logic, and linguistic theory to speak about the formal system behavior of symbolic systems, setting aside the symbols' meaning.
For example, logician C. I. Lewis wrote in 1918:
According to Jean E. Sammet, "the first realistic string handling and pattern matching language" for computers was COMIT in the 1950s, followed by the SNOBOL language of the early 1960s.
languages such as Chinese language, Japanese, and Korean language (known collectively as CJK characters) need far more than 256 characters (the limit of a one 8-bit byte per-character encoding) for reasonable representation. The normal solutions involved keeping single-byte representations for ASCII and using two-byte representations for CJK ideographs. Use of these with existing code led to problems with matching and cutting of strings, the severity of which depended on how the character encoding was designed. Some encodings such as the EUC family guarantee that a byte value in the ASCII range will represent only that ASCII character, making the encoding safe for systems that use those characters as field separators. Other encodings such as ISO-2022 and Shift-JIS do not make such guarantees, making matching on byte codes unsafe. These encodings also were not "self-synchronizing", so that locating character boundaries required backing up to the start of a string, and pasting two strings together could result in corruption of the second string.
Unicode has simplified the picture somewhat. Most programming languages now have a datatype for Unicode strings. Unicode's preferred byte stream format UTF-8 is designed not to have the problems described above for older multibyte encodings. UTF-8, UTF-16 and UTF-32 require the programmer to know that the fixed-size code units are different from the "characters", the main difficulty currently is incorrectly designed APIs that attempt to hide this difference (UTF-32 does make code points fixed-sized, but these are not "characters" due to composing codes).
Strings are typically implemented as arrays of bytes, characters, or code units, to allow fast access to individual units or substrings, including characters when they have a fixed length. A few languages such as Haskell implement them as instead.
Many high-level languages provide strings as a primitive data type, such as JavaScript and PHP, while most others provide them as a composite data type, some with special language support in writing literals, for example, Java and C#.
Some languages, such as C, Prolog and Erlang, avoid implementing a dedicated string datatype at all, instead adopting the convention of representing strings as lists of character codes. Even in programming languages having a dedicated string type, strings can usually be iterated as a sequence of character codes, like lists of integers or other values.
The term byte string usually indicates a general-purpose string of bytes, rather than strings of only (readable) characters, strings of bits, or such. Byte strings often imply that bytes can take any value and any data can be stored as-is, meaning that there should be no value interpreted as a termination value.
Most string implementations are very similar to variable-length arrays with the entries storing the of corresponding characters. The principal difference is that, with certain encodings, a single logical character may take up more than one entry in the array. This happens, for example, with UTF-8, where single codes (UCS code points) can take anywhere from one to four bytes, and single characters can take an arbitrary number of codes. In these cases, the logical length of the string (number of characters) differs from the physical length of the array (number of bytes in use). UTF-32 avoids the first part of the problem.
In terminated strings, the terminating code is not an allowable character in any string. Strings with length field do not have this limitation and can also store arbitrary binary data.
An example of a null-terminated string stored in a 10-byte buffer, along with its ASCII (or more modern UTF-8) representation as 8-bit hexadecimal numbers is:
The length of the string in the above example, "R", is 5 characters, but it occupies 6 bytes. Characters after the terminator do not form part of the representation; they may be either part of other data or just garbage. (Strings of this form are sometimes called ASCIZ strings, after the original assembly language directive used to declare them.)
Somewhat similar, "data processing" machines like the IBM 1401 used a special word mark bit to delimit strings at the left, where the operation would start at the right. This bit had to be clear in all other parts of the string. This meant that, while the IBM 1401 had a seven-bit word, almost no-one ever thought to use this as a feature, and override the assignment of the seventh bit to (for example) handle ASCII codes.
Early microcomputer software relied upon the fact that ASCII codes do not use the high-order bit, and set it to indicate the end of a string. It must be reset to 0 prior to output.
If the length is bounded, then it can be encoded in constant space, typically a machine word, thus leading to an implicit data structure, taking n + k space, where k is the number of characters in a word (8 for 8-bit ASCII on a 64-bit machine, 1 for 32-bit UTF-32/UCS-4 on a 32-bit machine, etc.).
If the length is not bounded, encoding a length n takes log( n) space (see fixed-length code), so length-prefixed strings are a succinct data structure, encoding a string of length n in log( n) + n space.
In the latter case, the length-prefix field itself does not have fixed length, therefore the actual string data needs to be moved when the string grows such that the length field needs to be increased.
Here is a Pascal string stored in a 10-byte buffer, along with its ASCII / UTF-8 representation:
However, since the implementation is usually hidden, the string must be accessed and modified through member functions. $ is a pointer to a dynamically allocated memory area, which might be expanded as needed. See also string (C++).
Both of these limitations can be overcome by clever programming.
It is possible to create data structures and functions that manipulate them that do not have the problems associated with character termination and can in principle overcome length code bounds. It is also possible to optimize the string represented using techniques from run length encoding (replacing repeated characters by the character value and a length) and Hamming coding.
While these representations are common, others are possible. Using ropes makes certain string operations, such as insertions, deletions, and concatenations more efficient.
The core data structure in a text editor is the one that manages the string (sequence of characters) that represents the current state of the file being edited.
While that state could be stored in a single long consecutive array of characters, a typical text editor instead uses an alternative representation as its sequence data structure—a gap buffer, a linked list of lines, a piece table, or a rope—which makes certain string operations, such as insertions, deletions, and undoing previous edits, more efficient.
Charles Crowley.
"Data Structures for Text Sequences" .
Section
"Introduction" .
String data is frequently obtained from user input to a program. As such, it is the responsibility of the program to validate the string to ensure that it represents the expected format. Performing limited or no validation of user input can cause a program to be vulnerable to code injection attacks.
Two common representations are:
C programmers draw a sharp distinction between a "string", aka a "string of characters", which by definition is always null terminated, vs. an "array of characters" which may be stored in the same array but is often not null terminated.
Using C string handling functions on such an array of characters often seems to work, but later leads to security problems.
"strlcpy and strlcat - consistent, safe, string copy and concatenation."
"A rant about strcpy, strncpy and strlcpy."
Keith Thompson.
"No, strncpy() is not a "safer" strcpy()".
2012.
Some categories of algorithms include:
Advanced string algorithms often employ complex mechanisms and data structures, among them and finite-state machines.
Many Unix utilities perform simple string manipulations and can be used to easily program some powerful string processing algorithms. Files and finite streams may be viewed as strings.
Some APIs like Multimedia Control Interface, embedded SQL or printf use strings to hold commands that will be interpreted.
Many scripting programming languages, including Perl, Python, Ruby, and Tcl employ regular expressions to facilitate text operations. Perl is particularly noted for its regular expression use, and many other languages and applications implement Perl compatible regular expressions.
Some languages such as Perl and Ruby support string interpolation, which permits arbitrary expressions to be evaluated and included in string literals.
The most basic example of a string function is the string length function – the function that returns the length of a string (not counting any terminator characters or any of the string's internal structural information) and does not modify the string. This function is often named F, R, or A. For example, N would return 11. Another common function is concatenation, where a new string is created by appending two strings, often this is the + addition operator.
Some microprocessor's instruction set architectures contain direct support for string operations, such as block copy (e.g. In intel x86m K).
The length of a string is the number of symbols in (the length of the sequence) and can be any non-negative integer; it is often denoted as . The empty string is the unique string over of length , and is denoted or . Here: sect.1.1, p.1
The set of all strings over of length is denoted . For example, if , then . We have for every alphabet .
The set of all strings over of any length is the Kleene star of and is denoted . In terms of ,
A set of strings over (i.e. any subset of ) is called a formal language over . For example, if , the set of strings with an even number of zeros, , is a formal language over .
String concatenation is an associative, but non-commutative operation. The empty string serves as the identity element; for any string , . Therefore, the set and the concatenation operation form a monoid, the free monoid generated by . In addition, the length function defines a monoid homomorphism from to the non-negative integers (that is, a function , such that ).
A string is said to be a substring or factor of if there exist (possibly empty) strings and such that . The binary relation "is a substring of" defines a partial order on , the least element of which is the empty string.
See Shortlex for an alternative string ordering that preserves well-foundedness.
For the example alphabet, the shortlex order is
The natural topology on the set of fixed-length strings or variable-length strings is the discrete topology, but the natural topology on the set of infinite strings is the limit topology, viewing the set of infinite strings as the inverse limit of the sets of finite strings. This is the construction used for the p-adic and some constructions of the Cantor set, and yields the same topology.
between string representations of topologies can be found by normalizing according to the lexicographically minimal string rotation.
History
A mathematical system is any set of strings of recognisable marks in which some of the strings are taken initially and the remainder derived from these by operations performed according to rules which are independent of any meaning assigned to the marks. That a system should consist of 'marks' instead of sounds or odours is immaterial.
String datatypes
String length
Character encoding
Implementations
Representations
Dope vectors
Null-terminated
F [[NUL>Null character]] kefw 4B16 0016 6B16 6516 6616 7716
Byte- and bit-terminated
Length-prefixed
length FRANK kefw 0516 4B16 6B16 6516 6616 7716
Strings as records
private unsigned long length; // string length
private UniquePointer
// public methods...
}
Other representations
Security concerns
Literal strings
Non-text strings
String processing algorithms
Character string-oriented languages and utilities
Character string functions
Formal theory
For example, if , then . Although the set itself is countably infinite, each element of is a string of finite length.
Concatenation and substrings
Prefixes and suffixes
Reversal
Rotations
Lexicographical ordering
String operations
Topology
See also
Explanatory notes
|
|